package com.molyfun.parents.activity.classroom;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.dao.entity.SingleChatDB;
import com.molyfun.parents.dao.gen.DaoMaster;
import com.molyfun.parents.dao.gen.DaoSession;
import com.molyfun.parents.dao.gen.SingleChatDBDao;
import com.molyfun.parents.rest.bean.CreateSingleConversionRequest;
import com.molyfun.parents.rest.bean.StringResponse;
import com.molyfun.parents.utils.AndroidBug5497Workaround;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.view.StrokeTextView;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.molyfun.parents.activity.classroom.ClassRoomActivity.FLAG_CLASS_IS_EXPIRE;

/**
 * Created by william(liuchao.hit@gmail.com).
 */

public class ClassRoomAllUsersActivity extends BaseActivity implements View.OnClickListener {

    @InjectView(R.id.title)
    StrokeTextView mTitle;
    @InjectView(R.id.base_title_left)
    ImageView mBackBtn;
    @InjectView(R.id.user_layout)
    LinearLayout mUserLayout;

//    private SingleChatDBDao mSingleChatDBDao;

    private List<TeamUser> mUserList;

    private static final String FLAG_TEAM_USERS = "team_users";

    private boolean isExpire;//课程是否过期

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_classroom_all_user);
        AndroidBug5497Workaround.assistActivity(this);
        getSupportActionBar().setTitle("");
        super.onCreate(savedInstanceState);
        ButterKnife.inject(this);
        mBackBtn.setOnClickListener(this);
        mTitle.setText("全部群成员");

//        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
//        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
//        DaoSession daoSession = daoMaster.newSession();
//        mSingleChatDBDao = daoSession.getSingleChatDBDao();


        isExpire = getIntent().getBooleanExtra(FLAG_CLASS_IS_EXPIRE, false);
        getTeamMemberList();

    }

    public static final void startActivity(Context context, ArrayList<TeamUser> teamUsers, boolean isExpire) {
        Intent intent = new Intent();
        intent.setClass(context, ClassRoomAllUsersActivity.class);
        intent.putParcelableArrayListExtra(FLAG_TEAM_USERS, teamUsers);
        intent.putExtra(FLAG_CLASS_IS_EXPIRE, isExpire);
        context.startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_title_left:
                finish();
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void getTeamMemberList() {
        mUserList = getIntent().getParcelableArrayListExtra(FLAG_TEAM_USERS);
        mUserLayout.removeAllViews();
        if (mUserList != null && mUserList.size() > 0) {

            int recycleCount = mUserList.size() / 3;
            if ((mUserList.size() % 3) > 0) {
                recycleCount += 1;
            }
            for (int position = 0; position < recycleCount; position++) {
                View view = LayoutInflater.from(ClassRoomAllUsersActivity.this).inflate(R.layout.layout_class_three_user_horizonal_cell, null, false);
                CircleImageView imageView1 = (CircleImageView) view.findViewById(R.id.avator1);
                CircleImageView imageView2 = (CircleImageView) view.findViewById(R.id.avator2);
                CircleImageView imageView3 = (CircleImageView) view.findViewById(R.id.avator3);

                ImageView admin1 = (ImageView) view.findViewById(R.id.admin1);
                ImageView admin2 = (ImageView) view.findViewById(R.id.admin2);
                ImageView admin3 = (ImageView) view.findViewById(R.id.admin3);

                TextView userName1 = (TextView) view.findViewById(R.id.user_name1);
                TextView studentName1 = (TextView) view.findViewById(R.id.student_name1);
                TextView userName2 = (TextView) view.findViewById(R.id.user_name2);
                TextView studentName2 = (TextView) view.findViewById(R.id.student_name2);
                TextView userName3 = (TextView) view.findViewById(R.id.user_name3);
                TextView studentName3 = (TextView) view.findViewById(R.id.student_name3);

                final TeamUser teamUser1 = mUserList.get(position * 3);
                if (!TextUtils.isEmpty(teamUser1.getHeadimgurl())) {
                    Picasso.with(ClassRoomAllUsersActivity.this)
                            .load(teamUser1.getHeadimgurl())
                            .placeholder(R.mipmap.ic_header_default)
                            .into(imageView1);
                } else {
                    imageView1.setImageResource(R.mipmap.ic_header_default);
                }
                userName1.setText(teamUser1.getUsername());
                if(!TextUtils.isEmpty(teamUser1.getUsertype()) && teamUser1.getUsertype().equals("1")){
                    admin1.setVisibility(View.GONE);
                    studentName1.setVisibility(View.VISIBLE);
                    studentName1.setText(teamUser1.getStudentname());
                }else{
                    admin1.setVisibility(View.VISIBLE);
                    studentName1.setVisibility(View.GONE);
                }
                imageView1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startSingleConversion(teamUser1.getUsertype(), teamUser1.getUserid(), teamUser1.getUsername(), teamUser1.getHeadimgurl());
                    }
                });

                if (position * 3 + 1 < mUserList.size()) {
                    final TeamUser teamUser2 = mUserList.get(position * 3 + 1);
                    if (!TextUtils.isEmpty(teamUser2.getHeadimgurl())) {
                        Picasso.with(ClassRoomAllUsersActivity.this)
                                .load(teamUser2.getHeadimgurl())
                                .placeholder(R.mipmap.ic_header_default)
                                .into(imageView2);
                    } else {
                        imageView2.setImageResource(R.mipmap.ic_header_default);
                    }
                    userName2.setText(teamUser2.getUsername());
                    if(!TextUtils.isEmpty(teamUser2.getUsertype()) && teamUser2.getUsertype().equals("1")){
                        studentName2.setVisibility(View.VISIBLE);
                        admin2.setVisibility(View.GONE);
                    }else{
                        studentName2.setVisibility(View.GONE);
                        admin2.setVisibility(View.VISIBLE);
                    }
                    imageView2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startSingleConversion(teamUser2.getUsertype(), teamUser2.getUserid(), teamUser2.getUsername(), teamUser2.getHeadimgurl());
                        }
                    });
                }


                if (position * 3 + 2 < mUserList.size()) {
                    final TeamUser teamUser3 = mUserList.get(position * 3 + 2);
                    if (!TextUtils.isEmpty(teamUser3.getHeadimgurl())) {
                        Picasso.with(ClassRoomAllUsersActivity.this)
                                .load(teamUser3.getHeadimgurl())
                                .placeholder(R.mipmap.ic_header_default)
                                .into(imageView3);
                    } else {
                        imageView3.setImageResource(R.mipmap.ic_header_default);
                    }
                    userName3.setText(teamUser3.getUsername());
                    if(!TextUtils.isEmpty(teamUser3.getUsertype()) && teamUser3.getUsertype().equals("1")){
                        studentName3.setVisibility(View.VISIBLE);
                        admin3.setVisibility(View.GONE);
                    }else{
                        studentName3.setVisibility(View.GONE);
                        admin3.setVisibility(View.VISIBLE);
                    }
                    imageView3.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startSingleConversion(teamUser3.getUsertype(), teamUser3.getUserid(), teamUser3.getUsername(), teamUser3.getHeadimgurl());
                        }
                    });
                }
                mUserLayout.addView(view);
            }

        }

    }

    private void startSingleConversion(final String type, final String userId, final String userName, final String cover) {
        if(isExpire){
            toast("课程已经过期，不能聊天");
            return;
        }
        if(!TextUtils.isEmpty(userId) && userId.equals(MFPApplication.getInstance().getUser().getId())){
            toast("不能和自己聊天");
            return;
        }
        showProgressDialog();
        CreateSingleConversionRequest createSingleConversionRequest = new CreateSingleConversionRequest();
        createSingleConversionRequest.setTarget(userId);
        createSingleConversionRequest.setTargettype(type);
        Call<StringResponse> call = MFPApplication.getInstance().getRestClient().createSingleConversation(createSingleConversionRequest);
        call.enqueue(new Callback<StringResponse>() {
            @Override
            public void onResponse(Call<StringResponse> call, Response<StringResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if (!TextUtils.isEmpty(response.body().getData())) {
                        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
                        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
                        DaoSession daoSession = daoMaster.newSession();
                        SingleChatDBDao mSingleChatDBDao = daoSession.getSingleChatDBDao();
                        SingleChatDB singleChatDB = mSingleChatDBDao.queryBuilder().where(SingleChatDBDao.Properties.Conversationid.eq(response.body().getData())).build().unique();
                        if (singleChatDB != null) {
                            int unreadCount = singleChatDB.getUnReadMsgCount();
                            singleChatDB.setUnReadMsgCount(unreadCount + 1);
                            singleChatDB.setLastMsgTime(System.currentTimeMillis());
                        } else {
                            singleChatDB = new SingleChatDB();
                            singleChatDB.setConversationid(response.body().getData());
                            singleChatDB.setTxuserid(PreferencesStorageUtil.getIMUserName(ClassRoomAllUsersActivity.this));
                            singleChatDB.setCover(cover);
                            singleChatDB.setLastMsgTime(System.currentTimeMillis());
                            singleChatDB.setUnReadMsgCount(1);
                            singleChatDB.setTxuserid(PreferencesStorageUtil.getIMUserName(ClassRoomAllUsersActivity.this));

                            singleChatDB.setName(userName);
                            singleChatDB.setIsTeam(false);
                            singleChatDB.setUserId(userId);
                            singleChatDB.setTargettype(type);
                        }
                        mSingleChatDBDao.insertOrReplace(singleChatDB);

                        SingleChatActivity.startActivity(ClassRoomAllUsersActivity.this, response.body().getData(), userId, userName, type);
                    }
                }
            }

            @Override
            public void onFailure(Call<StringResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

}
